package com.zyy.game.tianlong.tool;

import com.zyy.game.tianlong.TianlongApplication;
import com.zyy.game.tianlong.network.exception.LogicException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.system.ApplicationHome;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author relufi
 * @date 2019/8/12 0012
 */
public class WebUtils {

    public static File CLASS_PATH = new ApplicationHome(TianlongApplication.class).getSource();

    public static String getUuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * get
     *
     * @param url url地址
     * @return 返回字符串信息
     */
    public static String sendGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
            return null;
        } catch (IOException e) {
            throw new LogicException("http客户端GET错误", e);
        }
    }

    /**
     * Post 请求
     *
     * @param url url地址
     * @param map 参数
     * @return 返回字符串信息
     */
    public static String sendPost(String url, Map<String, String> map) {
        List<NameValuePair> formParams = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(formEntity);

        try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
            return null;
        } catch (IOException e) {
            throw new LogicException("http客户端POST错误", e);
        }
    }

}
